using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Boggle.Net.Controls
{
    public class AutoGrayableImage : Image
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoGrayableImage"/> class.
        /// </summary>
        static AutoGrayableImage()
        {
            // Override the metadata of the IsEnabled property.
            IsEnabledProperty.OverrideMetadata(typeof(AutoGrayableImage), new FrameworkPropertyMetadata(true, OnAutograyScaleImageIsEnabledPropertyChanged));
        }
        /// <summary>
        /// Called when [auto gray scale image is enabled property changed].
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="args">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnAutograyScaleImageIsEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            var autoGrayableImage = source as AutoGrayableImage;
            if (autoGrayableImage == null) return;

            if (!Convert.ToBoolean(args.NewValue))
            {
                var bitmapImage = new BitmapImage(new Uri(autoGrayableImage.Source.ToString()));

                autoGrayableImage.Source = new FormatConvertedBitmap(bitmapImage, PixelFormats.Gray32Float, null, 0);
                autoGrayableImage.OpacityMask = new ImageBrush(bitmapImage);
            }
            else
            {
                autoGrayableImage.Source = ((FormatConvertedBitmap)autoGrayableImage.Source).Source;
                autoGrayableImage.OpacityMask = null;
            }
        }
    }
}